﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using NHibernate.Cfg;
using Telerik.Windows.Controls;
using Broker.View;
using Broker.Model;
using BrokerBase.Lib.Client;
using BrokerBase.Lib.Company;
using BrokerBase.Lib.Core;
using Broker.Comm;
using log4net;
using System.Data.SQLite;
using NHibernate;
using BrokerBase.Lib.Product;
using NHibernate.Criterion;
using System.ServiceModel;
using Broker.Update;
using Broker.View.ViewModel;
using System.Threading;
using Broker.DataService;
using System.Windows.Media;
using Telerik.Windows.Controls.Navigation;

namespace Broker
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private Thread loadDataThread;

        public App()
        {
            StyleManager.ApplicationTheme = new MetroTheme();

            this.Startup += new StartupEventHandler(App_Startup);
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            //Test();

            try
            {
                MetroColors.PaletteInstance.AccentColor = Color.FromRgb(112,146,190);

               
                SqliteCollate();//在sqlite中注入拼音排序

                //ILog log = log4net.LogManager.GetLogger(this.GetType());

                AppGlobal.Log = CreateLog();

                BrokerBase.Lib.BaseLibGlobal.Log = AppGlobal.Log;

                Configuration cfg = new Configuration();
                cfg.Configure();

                IDictionary<string, string> dict = cfg.Properties;
                //客户端数据库密码
                //F82C61E55D0A48ADABD07F4600DAD7D49

                string path = AppGlobal.GetAppPath();   //System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);

                string dbpath = AppGlobal.GetAppPath() + @"\broker.db";

                cfg.SetProperty("connection.connection_string", "Data Source=" + dbpath + ";collate =PinYin;Version=3;Password=" + ClientUtil.Evdb());

                AppGlobal.HbmSessionFactory = cfg.BuildSessionFactory();

                NHibernate.Context.ThreadStaticSessionContext.Bind(AppGlobal.HbmSessionFactory.OpenSession());

                AppGlobal.ClientCfg = ClientConfiguration.Load(AppGlobal.GetAppPath() + @"\" + ClientConfiguration.USER_FILE_NAME);
                SetConfig();

                AppGlobal.DataWCF = RemoteDataService.GetInstance();

                Broker.View.LibGlobal.HbmSessionFactory = AppGlobal.HbmSessionFactory;

                AsyncLoadData();// 异步读取数据

                Broker.View.LibGlobal.BaseDataType = AppGlobal.BaseDataType;

                Broker.View.LibGlobal.AppType = AppType.Business;

                Broker.View.LibGlobal.LoadTrialProduct = AppGlobal.LoadTrialProductId;

                Broker.View.LibGlobal.IsActiveCallBack = () =>
                    {
                        return LicenseInfo.GetInstance().IsEffective;
                    };

                Broker.View.LibGlobal.GetCurrentCompany = () =>
                    {
                        return AppGlobal.CurrentCompany;
                    };

                Broker.View.LibGlobal.GetClientCfg = () =>
                    {
                        return AppGlobal.ClientCfg;
                    };

                //Broker.View.LibGlobal.GetAppDataPath = () =>
                //    {
                //        return AppGlobal.GetAppDataPath();
                //    };

                Broker.View.LibGlobal.GetAppPath = () =>
                    {
                        return AppGlobal.GetAppPath();
                    };

                Broker.View.LibGlobal.DarkBackground = Application.Current.Resources["DarkBackground"] as SolidColorBrush;

                LoadUser();

                AppGlobal.DataWCF.User = AppGlobal.CurrentUser;
                AppGlobal.DataWCF.Start();

                MainNewForm mainForm = new MainNewForm();
                

                Window mf = mainForm.ParentOfType<Window>();

                App.Current.MainWindow = mf;

                Broker.View.LibGlobal.MainWindow = mf;
                Broker.View.LibGlobal.MainWin = mainForm;

                mainForm.Show();



                //App.Current.MainWindow = frm.ParentOfType<MainNewWindow>();

                //App.Current.MainWindow.ShowInTaskbar = true;

                //MainForm from = new MainForm();
                //from.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                //from.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void LoadUser()
        {
            if (!LicenseInfo.GetInstance().IsEffective)
            {
                ISession sess = null;
                ITransaction tx = null;

                try
                {
                    sess = AppGlobal.HbmSessionFactory.OpenSession();

                    tx = sess.BeginTransaction();

                    ISQLQuery q = sess.CreateSQLQuery("delete from sys_user");
                    q.ExecuteUpdate();

                    q = sess.CreateSQLQuery("delete from Score_ScoreRecord");
                    q.ExecuteUpdate();

                    tx.Commit();
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    AppGlobal.Log.Error("删除用户时发生错误", ex);
                }
                finally
                {
                    sess.Close();
                }

            }
            else
            {
                ISession sess=AppGlobal.HbmSessionFactory.GetCurrentSession();

                SysUser user = sess.CreateQuery("from SysUser").UniqueResult<SysUser>();

                AppGlobal.CurrentUser = user;
            }
        }

        private ILog CreateLog()
        {
            string path = AppGlobal.GetAppPath() + @"\log-file.txt";

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%d %p %m %n");
            log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender(layout, path, true);

            log4net.Filter.LevelRangeFilter lrf = new log4net.Filter.LevelRangeFilter();

            lrf.LevelMin = log4net.Core.Level.Error;
            lrf.LevelMax = log4net.Core.Level.Error;

            appender.AddFilter(lrf);


            log4net.Config.BasicConfigurator.Configure(appender);

            ILog log = LogManager.GetLogger(this.GetType());

            return log;
        }

        private void SetConfig()
        {

            if (AppGlobal.ClientCfg.DefaultCompany == "[全部]")
            {
                ICompany cmp = new Company();
                cmp.Name = "[全部]";
                cmp.Id = 0;

                AppGlobal.CurrentCompany = cmp;
            }
            else
            {

                IBaseService<Company> svr = new BaseService<Company>(AppGlobal.HbmSessionFactory.GetCurrentSession());

                ICompany cmp = svr.GetByHQL(string.Format("from Company where Name ='{0}'", AppGlobal.ClientCfg.DefaultCompany));

                AppGlobal.CurrentCompany = cmp;
            }
        }

        public void AsyncLoadData()
        {
            try
            {
                loadDataThread = new Thread(LoadData);
                loadDataThread.Start();
                
            }
            catch (Exception ex)
            {
                AppGlobal.Log.Error("异步读取数据是发生错误", ex);
            }
        }

        public void LoadData()
        {
            LibGlobal.ProductNames = ProductNameModel.LoadAllBasic(0);

            LibGlobal.PersonNames = PersonNameModel.LoadAllPerson();
        }

        public void Login()
        {
            LoginForm frm = new LoginForm();

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = AppGlobal.MainWin;
            frm.ShowDialog();
        }

        private void SqliteCollate()
        {

            SQLiteFunction.RegisterFunction(typeof(SQLiteCollation_PinYin));    // 注入拼音排序，
        }

        private void CheckUser()
        {

        }

        private void Test()
        {
            ChannelFactory<IDataService> factory = AppGlobal.CreateDataServiceFactory();

            IDataService ser = factory.CreateChannel();

            
            
        }
    
    
    }
    [SQLiteFunction(FuncType = FunctionType.Collation, Name = "PinYin")]
    class SQLiteCollation_PinYin : SQLiteFunction
    {
        public override int Compare(string x, string y)
        {
            return string.Compare(x, y);
        }
    }

    class dect : NHibernate.Dialect.SQLiteDialect
    {
        
        
    }

    

}
